package com.ctg.itrdc.sysmgr.portal.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.pasp.context.service.BaseService;
import com.ctg.itrdc.sysmgr.portal.api.dto.PrivGrantDTO;
import com.ctg.itrdc.sysmgr.portal.api.service.IPrivGrantService;
import com.ctg.itrdc.sysmgr.portal.common.constant.PrivGrantEnum.GrantSysobjType;
import com.ctg.itrdc.sysmgr.portal.data.IPrivGrantDao;
import com.ctg.itrdc.sysmgr.portal.data.entity.PrivGrant;
import com.ctg.itrdc.sysmgr.portal.service.utils.BeanUtils;
import com.google.common.collect.Lists;

@Component("privGrantService")
public class PrivGrantServiceImpl extends BaseService<PrivGrant, Long, PrivGrantDTO>
		implements IPrivGrantService {
	@Resource
	private IPrivGrantDao privGrantDao;

	@Override
	public void batchDeleteByPrivIds(String ids, PrivGrantDTO dto) {
		List<Long> privIdList = Lists.newArrayList();
		String[] privIds = ids.split(",");
		for (String privId : privIds) {
			privIdList.add(Long.parseLong(privId));
		}
		PrivGrant entity = BeanUtils.applyIfNotException(dto, PrivGrant.class);
		privGrantDao.batchDeleteByPrivIds(privIdList,entity);
	}

	@Override
	public List<PrivGrantDTO> batchInsert(String ids,PrivGrantDTO dto) {
		List<PrivGrantDTO> dtoList = Lists.newArrayList();
		String[] arr = ids.split(",");
		for (String obj : arr) {
			long privId = Long.parseLong(obj);
			PrivGrantDTO tmp = BeanUtils.applyIfNotException(dto, PrivGrantDTO.class);
			tmp.setPrivId(privId);
			if(dto.getGrantObjType()!=null)
				tmp.setGrantObjType(GrantSysobjType.valueOf(dto.getGrantObjType()).toString());
			if(!exists(tmp))
				dtoList.add(tmp);
		}
		if(CollectionUtils.isNotEmpty(dtoList)) {
			List<PrivGrant> entities = BeanUtils.copyListNotException(dtoList, PrivGrant.class);
			privGrantDao.jdbcBatchInsert(entities);
		}
		
		return selectByList(dtoList);
	}
	
	private List<PrivGrantDTO> selectByList(List<PrivGrantDTO> dtoList){
		List<PrivGrantDTO> result = Lists.newArrayList();
		for (PrivGrantDTO param : dtoList) {
			List<PrivGrantDTO> list = this.selectByExample(param);
			result.addAll(list);
		}
		return result;
	}

}
